const express = require('express')
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const { body, param, validationResult } = require('express-validator')
const User = require('../models/user.model')
const Video = require('../models/video.model')
const { authMiddleware } = require('../middlewares/auth.middleware')
const userSettingsController = require('../controllers/userSettings.controller')
const router = express.Router()

// 配置头像上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = path.join(__dirname, '../../uploads/avatars')
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true })
    }
    cb(null, uploadDir)
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, uniqueSuffix + path.extname(file.originalname))
  }
})

const upload = multer({
  storage,
  limits: {
    fileSize: 2 * 1024 * 1024 // 2MB
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true)
    } else {
      cb(new Error('不支持的图片格式'))
    }
  }
})

// 获取当前用户资料
router.get('/profile', authMiddleware, async (req, res) => {
  try {
    const user = await User.findById(req.user._id)
      .select('-password -watchHistory');

    if (!user) {
      return res.status(404).json({ success: false, message: '用户不存在' });
    }

    const stats = await user.getStats();
    res.json({ 
      success: true,
      user: { 
        ...user.toObject(), 
        stats,
        followersCount: user.subscribers?.length || 0,
        followingCount: user.subscribedTo?.length || 0
      } 
    });
  } catch (error) {
    console.error('获取用户资料失败:', error);
    res.status(500).json({ success: false, message: '获取用户资料失败' });
  }
});

// 更新用户信息
router.put('/profile', [
  authMiddleware,
  body('username').optional().trim().isLength({ min: 2, max: 30 }),
  body('email').optional().trim().isEmail(),
  body('bio').optional().trim().isLength({ max: 200 })
], async (req, res) => {
  try {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, errors: errors.array() })
    }

    const { username, email, bio } = req.body;

    // 检查用户名和邮箱是否已被其他用户使用
    if (username || email) {
      const existingUser = await User.findOne({
        _id: { $ne: req.user._id },
        $or: [
          ...(username ? [{ username }] : []),
          ...(email ? [{ email }] : [])
        ]
      });

      if (existingUser) {
        return res.status(400).json({
          success: false,
          message: '用户名或邮箱已被使用'
        });
      }
    }

    const updates = {}
    if (username) updates.username = username
    if (email) updates.email = email
    if (bio !== undefined) updates.bio = bio

    const user = await User.findByIdAndUpdate(
      req.user._id,
      { $set: updates },
      { new: true, runValidators: true }
    ).select('-password')

    res.json({ success: true, user })
  } catch (error) {
    console.error('更新用户信息失败:', error)
    if (error.name === 'ValidationError') {
      return res.status(400).json({
        success: false,
        message: '验证失败',
        errors: Object.values(error.errors).map(err => err.message)
      });
    }
    res.status(500).json({ success: false, message: '更新用户信息失败' })
  }
})

const BASE_URL = process.env.BASE_URL || 'http://localhost:3000'; // 获取基础 URL

// 上传头像
router.post('/avatar', authMiddleware, upload.single('avatar'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ success: false, message: '请上传头像文件' });
    }

    // 构建头像 URL，注意 uploads 目录是相对于项目根目录的
    // 需要确保前端能访问到这个路径，可能需要配置静态文件服务
    const avatarUrl = `${BASE_URL}/uploads/avatars/${req.file.filename}`;

    // 更新用户头像 URL
    const user = await User.findByIdAndUpdate(
      req.user._id,
      { $set: { avatar: avatarUrl } },
      { new: true }
    ).select('-password');

    if (!user) {
      return res.status(404).json({ error: '用户不存在' });
    }

    res.json({ success: true, avatarUrl: user.avatar });
  } catch (error) {
    console.error('上传头像失败:', error);
    // 处理 multer 的错误
    if (error instanceof multer.MulterError) {
      if (error.code === 'LIMIT_FILE_SIZE') {
        return res.status(400).json({ error: '头像文件大小不能超过 2MB' });
      }
    }
    // 处理文件类型错误
    if (error.message === '不支持的图片格式') {
        return res.status(400).json({ error: '头像图片只能是 JPG, PNG 或 GIF 格式' });
    }
    res.status(500).json({ error: '上传头像失败' });
  }
});

// 获取用户信息
router.get('/:userId', async (req, res) => {
  try {
    console.log(`获取用户信息，用户ID: ${req.params.userId}`);
    const user = await User.findById(req.params.userId)
      .select('-password -watchHistory')
      .populate('videos', 'title thumbnail views createdAt')

    if (!user) {
      console.log(`用户不存在，ID: ${req.params.userId}`);
      return res.status(404).json({ error: '用户不存在' })
    }

    const stats = await user.getStats()
    res.json({ user: { ...user.toObject(), stats } })
  } catch (error) {
    console.error('获取用户信息失败:', error)
    res.status(500).json({ error: '获取用户信息失败' })
  }
})

// 获取用户视频列表
router.get('/:userId/videos', async (req, res) => {
  try {
    console.log(`获取用户视频列表，用户ID: ${req.params.userId}, 页码: ${req.query.page || 1}, 每页数量: ${req.query.limit || 20}`);
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const skip = (page - 1) * limit;

    // 构建基础查询条件
    const query = { user: req.params.userId };

    // 检查是否是视频所有者访问
    const isOwner = req.user?._id.equals(req.params.userId);

    // 如果不是所有者，则只显示已就绪的公开视频
    if (!isOwner) {
      query.status = 'ready';
      query.privacy = 'public';
    }
    // 如果是所有者，则显示所有状态和隐私的视频

    const videos = await Video.find(query)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit)
      .populate('user', 'username avatar');

    console.log(`查询到 ${videos.length} 个视频`);
    res.json({ videos });
  } catch (error) {
    console.error('获取用户视频列表失败:', error);
    res.status(500).json({ error: '获取用户视频列表失败' });
  }
});

// 订阅用户
router.post('/:userId/subscribe', authMiddleware, async (req, res) => {
  try {
    const { userId } = req.params

    // 不能订阅自己
    if (req.user._id.equals(userId)) {
      return res.status(400).json({ error: '不能订阅自己' })
    }

    const targetUser = await User.findById(userId)
    if (!targetUser) {
      return res.status(404).json({ error: '用户不存在' })
    }

    const user = await User.findById(req.user._id)

    // 检查是否已订阅
    const isSubscribed = user.subscribedTo.some(subscribedId => subscribedId.equals(userId));
    if (isSubscribed) {
      // 取消订阅
      user.subscribedTo = user.subscribedTo.filter(id => !id.equals(userId))
      targetUser.subscribers = targetUser.subscribers.filter(id => !id.equals(req.user._id))
    } else {
      // 添加订阅
      user.subscribedTo.push(userId)
      targetUser.subscribers.push(req.user._id)
    }

    await Promise.all([user.save(), targetUser.save()])

    res.json({
      message: isSubscribed ? '取消订阅成功' : '订阅成功',
      isSubscribed: !isSubscribed
    })
  } catch (error) {
    console.error('订阅操作失败:', error)
    res.status(500).json({ error: '订阅操作失败' })
  }
})

// 获取订阅的视频
router.get('/subscribed/videos', authMiddleware, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1
    const limit = parseInt(req.query.limit) || 20
    const skip = (page - 1) * limit

    const user = await User.findById(req.user._id)
    const videos = await Video.find({
      user: { $in: user.subscribedTo },
      status: 'ready',
      privacy: 'public'
    })
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit)
      .populate('user', 'username avatar')

    res.json({ videos })
  } catch (error) {
    console.error('获取订阅视频失败:', error)
    res.status(500).json({ error: '获取订阅视频失败' })
  }
})

// 检查是否已订阅特定用户
router.get('/:userId/subscribed', authMiddleware, async (req, res) => {
  try {
    const { targetId } = req.query;
    
    if (!targetId) {
      return res.status(400).json({ error: '缺少目标用户ID' });
    }
    
    const user = await User.findById(req.params.userId);
    if (!user) {
      return res.status(404).json({ error: '用户不存在' });
    }
    
    // 检查当前用户是否已经订阅了目标用户
    const isSubscribed = user.subscribedTo.some(id => id.toString() === targetId);
    
    res.json({ isSubscribed });
  } catch (error) {
    console.error('检查订阅状态失败:', error);
    res.status(500).json({ error: '检查订阅状态失败' });
  }
});

// 获取用户喜欢的视频
router.get('/liked/videos', authMiddleware, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1
    const limit = parseInt(req.query.limit) || 20
    const skip = (page - 1) * limit

    const user = await User.findById(req.user._id)
    const videos = await Video.find({
      _id: { $in: user.likedVideos },
      status: 'ready',
      privacy: 'public'
    })
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit)
      .populate('user', 'username avatar')

    res.json({ videos })
  } catch (error) {
    console.error('获取喜欢的视频失败:', error)
    res.status(500).json({ error: '获取喜欢的视频失败' })
  }
})

// 获取观看历史
router.get('/history/videos', authMiddleware, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1
    const limit = parseInt(req.query.limit) || 20
    const skip = (page - 1) * limit

    const user = await User.findById(req.user._id)
      .populate({
        path: 'watchHistory.video',
        match: { status: 'ready' },
        populate: { path: 'user', select: 'username avatar' }
      })
      .select('watchHistory')

    // 过滤掉已删除的视频
    const history = user.watchHistory
      .filter(item => item.video)
      .slice(skip, skip + limit)

    res.json({ history })
  } catch (error) {
    console.error('获取观看历史失败:', error)
    res.status(500).json({ error: '获取观看历史失败' })
  }
})

// 清空观看历史
router.delete('/history', authMiddleware, async (req, res) => {
  try {
    await User.findByIdAndUpdate(req.user._id, {
      $set: { watchHistory: [] }
    })

    res.json({ message: '观看历史已清空' })
  } catch (error) {
    console.error('清空观看历史失败:', error)
    res.status(500).json({ error: '清空观看历史失败' })
  }
})

// 获取稍后观看列表
router.get('/watchlater/videos', authMiddleware, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1
    const limit = parseInt(req.query.limit) || 15
    const skip = (page - 1) * limit

    const user = await User.findById(req.user._id)
      .populate({
        path: 'watchLater',
        options: {
          sort: { addedAt: -1 },
          skip,
          limit
        },
        populate: {
          path: 'user',
          select: 'username avatar'
        }
      })

    const totalVideos = user.watchLater.length
    const totalPages = Math.ceil(totalVideos / limit)

    res.json({
      videos: user.watchLater,
      currentPage: page,
      totalPages,
      totalVideos
    })
  } catch (error) {
    console.error('获取稍后观看列表失败:', error)
    res.status(500).json({ error: '获取稍后观看列表失败' })
  }
})

// 修改密码 (使用 userSettingsController)
router.put('/password', 
  authMiddleware, 
  [
    body('currentPassword').notEmpty().withMessage('当前密码不能为空'),
    body('newPassword').isLength({ min: 6 }).withMessage('新密码长度不能少于6位')
  ],
  (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  userSettingsController.updatePassword
);

// 修改邮箱 (使用 userSettingsController)
router.put('/email',
  authMiddleware,
  [
    body('newEmail').isEmail().withMessage('请输入有效的邮箱地址'),
    body('password').notEmpty().withMessage('请输入当前密码以验证身份')
  ],
  (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
  userSettingsController.updateEmail
);

// 获取两步验证设置
router.get('/2fa/setup', authMiddleware, userSettingsController.getTwoFactorSetup);

// 启用两步验证
module.exports = router